/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package intelligenttm;

import intelligenttm.ITMCarto.BaseData;
import intelligenttm.ITMCarto.S1SelectMapController;
import intelligenttm.ITMCarto.S2InputDataController;
import intelligenttm.ITMCarto.S3SelectionTypeController;
import intelligenttm.ITMCarto.SHierarchicalStatisticalGraphController;
import intelligenttm.ITMCarto.SPartitionSatisticalGraphController;
import intelligenttm.InPutDlg.SavePicControlDlgController;
import intelligenttm.SourceFile.CartoType;
import intelligenttm.SourceFile.SavePicControl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.List;
import javafx.event.*;

import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.Transcoder;

import org.apache.batik.transcoder.image.JPEGTranscoder;

import org.w3c.dom.Document;
import javafx.embed.swing.SwingNode;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import me.aviator.entity.MBasemap;

import org.apache.batik.transcoder.image.PNGTranscoder;

import org.apache.batik.transcoder.TranscoderInput;

import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.fop.svg.PDFTranscoder;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.svg.SVGAnimatedLength;
import org.w3c.dom.svg.SVGDocument;

/**
 *
 * @author 望舒凌霄
 */
public class ITMUIMethod {
    
    public void UIMainNewFile(DocNumCount SVGDocNumCount,List<SVGCarto> SVGCartoList,List DocTabList,TabPane UIMainTabPane){
        ImageView I=new ImageView("Pic/Icon/file.png");
        I.setFitHeight(20);
        I.setFitWidth(20);
        
        Tab NewTab=new Tab("空白文档"+(SVGDocNumCount.getNumCount()+1));
        NewTab.setId("CartoFile"+(SVGDocNumCount.getNumCount()+1));
        NewTab.setGraphic(I);
        
        SVGCarto S=null;
        SVGCartoList.add(S);
        
        ScrollPane P=new ScrollPane();
        NewTab.setContent(P);
        MenuItem TabContextMenuItem = new MenuItem("关闭");
        ImageView I2=new ImageView("Pic/Icon/close.png");
        I2.setFitHeight(20);
        I2.setFitWidth(20);
        TabContextMenuItem.setGraphic(I2);
        
        TabContextMenuItem.setOnAction(new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent ae){
                String TabCMID=TabContextMenuItem.getParentPopup().getId();
                int TabPNum=getTabPositionInTabPaneByCMId(UIMainTabPane,TabCMID);
                SVGDocNumCount.setDocNum(SVGDocNumCount.getDocNum()-1);
                DocTabList.remove(TabPNum);
                UIMainTabPane.getTabs().remove(TabPNum);
                SVGCartoList.remove(TabPNum);
            }
        });
        ContextMenu C=new ContextMenu(TabContextMenuItem);
        C.setId("Tab"+(SVGDocNumCount.getNumCount()+1)+"CMId");
        NewTab.setContextMenu(C);
        DocTabList.add(NewTab);
        UIMainTabPane.getTabs().add((Tab)DocTabList.get(SVGDocNumCount.getDocNum()));
        SVGDocNumCount.setDocNum(SVGDocNumCount.getDocNum()+1);
        SVGDocNumCount.setNumCount(SVGDocNumCount.getNumCount()+1);
    }
    
    public void UIMainOpenFile(List<SVGCarto> SVGCartoList,DocNumCount SVGDocNumCount,int NowDocIndex,List DocTabList,TabPane UIMainTabPane,TreeView<String> UIMainTOC) throws IOException, InterruptedException{
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("打开SVG文件");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); 
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("SVG", "*.svg"),
                new FileChooser.ExtensionFilter("All Files", "*.*")
        );
        Stage s = new Stage(); 
        File file = fileChooser.showOpenDialog(s);
        
        if (file != null) {
            String SVGFilePath=file.toURL().toString();
            SVGCarto S=new SVGCarto(SVGFilePath);
            
            if (NowDocIndex==-1){
                UIMainNewFile(SVGDocNumCount,SVGCartoList,DocTabList,UIMainTabPane);
                NowDocIndex=SVGDocNumCount.getDocNum()-1;
            }

            SVGCartoList.set(NowDocIndex, S);
            JSVGCanvas svgCanvas = new JSVGCanvas();
            svgCanvas.setDocument((Document)SVGCartoList.get(NowDocIndex).getSvgDocument());
//            ScrollPane SP=new ScrollPane();
//            svgCanvas.setEnableImageZoomInteractor(true);
//            svgCanvas.setEnablePanInteractor(true);
            
            
//            svgCanvas.setSize(400, 400);
            SwingNode SNsvgCanvas=new SwingNode ();
//            svgCanvas.setSize(1000, 1000);
            Thread.sleep(5000);
//            SVGAnimatedLength hh=SVGCartoList.get(NowDocIndex).getSvgDocument().getRootElement().;
            svgCanvas.resize(1000, 1000);
            
            int w=svgCanvas.getWidth();
            int h=svgCanvas.getHeight();
            SNsvgCanvas.setContent(svgCanvas);
            
            //
            //SNsvgCanvas.resize(1, 1);
//            SNsvgCanvas.setLayoutX(0);
//            SNsvgCanvas.setLayoutY(0);
            
//            SP.setContent(SNsvgCanvas);
//            SP.prefHeight(Region.USE_COMPUTED_SIZE);
//            SP.prefHeight(Region.USE_COMPUTED_SIZE);
//            SNsvgCanvas.prefWidth(Region.USE_COMPUTED_SIZE);
//            SNsvgCanvas.prefHeight(Region.USE_COMPUTED_SIZE);
            ((ScrollPane)(UIMainTabPane.getTabs().get(NowDocIndex).getContent())).setContent(SNsvgCanvas);
                    //getChildren().add(SNsvgCanvas);
            
            UIMainTabPane.getTabs().get(NowDocIndex).setText(SVGCartoList.get(NowDocIndex).getBasedSVGName());
            SetTOCTreeVew(S,UIMainTOC);
        }
        
        //
        
        //SVGCartoList.set(NowDocIndex, S);
    }
    
    public void UIRefreashNowSVGCanvas(List<SVGCarto> SVGCartoList, int NowDocIndex,TabPane UIMainTabPane){
        if(NowDocIndex>=0){
            JSVGCanvas svgCanvas = new JSVGCanvas();
            SwingNode SNsvgCanvas=new SwingNode ();
            
            svgCanvas.setDocument((Document)SVGCartoList.get(NowDocIndex).getSvgDocument());
            SNsvgCanvas.setContent(svgCanvas);
            svgCanvas.repaint();
            ((ScrollPane)(UIMainTabPane.getTabs().get(NowDocIndex).getContent())).getChildrenUnmodifiable().clear();
            ((ScrollPane)(UIMainTabPane.getTabs().get(NowDocIndex).getContent())).setContent(SNsvgCanvas);
            
        }
    }
    
    
    
    public int UITabPaneSelectedTab(TabPane UIMainTabPane){
        int Num=UIMainTabPane.getTabs().size();
        for (int i=0;i<Num;i++){
            if (UIMainTabPane.getTabs().get(i).isSelected()){
                return i;
            }
        }
        return -1;
    }
    
    public int getTabPositionInTabPaneById(TabPane UIMainTabPane,String Id){
        int Num=UIMainTabPane.getTabs().size();
        for (int i=0;i<Num;i++){
            String Tabid=UIMainTabPane.getTabs().get(i).getId();
            if (Tabid.equals(Id)){
                return i;
            }
        }
        return -1;
    }
    
    public int getTabPositionInTabPaneByCMId(TabPane UIMainTabPane,String CMId){
        int Num=UIMainTabPane.getTabs().size();
        for (int i=0;i<Num;i++){
            String TabCMid=UIMainTabPane.getTabs().get(i).getContextMenu().getId();
            if (TabCMid.equals(CMId)){
                return i;
            }
        }
        return -1;
    }
    
    public void UIMainSaveFile(SVGCarto OutSVGCarto) throws IOException, MalformedURLException, FileNotFoundException, TranscoderException{
        String SavePath=OutSVGCarto.getBasedSVGPath();
        if (SavePath==null){
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("保存SVG文件");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("SVG", "*.svg")
            );
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
            Stage s = new Stage(); 
            File file = fileChooser.showSaveDialog(s);
            if (file != null) {
                SavePath=file.getPath();
            }
        }
        if (SavePath!=null){
            
        }
        UIMainSaveAsFile(OutSVGCarto, SavePath,"svg");
    }
    
    public void UIMainSaveAsFile(SVGCarto OutSVGCarto,String SaveType) throws IOException, MalformedURLException, FileNotFoundException, TranscoderException{
        FileChooser fileChooser = new FileChooser();
        switch (SaveType){
            case "SaveAs":
                fileChooser.setTitle("另存为SVG文件");
                fileChooser.getExtensionFilters().addAll(
                        new FileChooser.ExtensionFilter("SVG", "*.svg")
                );
                break;
            case "OutPut":
                fileChooser.setTitle("导出文件");
                fileChooser.getExtensionFilters().addAll(
                        new FileChooser.ExtensionFilter("JPG图像", "*.jpg"),
                        new FileChooser.ExtensionFilter("PNG图像", "*.png"),
                        new FileChooser.ExtensionFilter("PDF文件", "*.pdf")
                );
                break;
            default:
                break;
        }
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); 
        
        Stage s = new Stage(); 
        File file = fileChooser.showSaveDialog(s);
        if (file != null) {
            
            String OutFilePath=file.getPath();
            String FileName=file.getName();
            
            if (FileName.length()>0){
                int i = FileName.lastIndexOf(".");
                if(i>-1 && i<FileName.length()){
                    String Name = FileName.substring(0, i); //--文件名
                    String Extention = FileName.substring(i+1); //--扩展名
                    if(SaveType=="OutPut"){
                        
                    }
                    UIMainSaveAsFile(OutSVGCarto, OutFilePath, Extention);
                }
            }
        }
    }
    
    
    
    public void UIMainSaveAsFile(SVGCarto OutSVGCarto, String OutFilePath, String OutType) throws IOException, MalformedURLException, FileNotFoundException, TranscoderException{
        switch (OutType){
            case "svg":
                SVGGraphics2D OutSVGGraphics2D = new SVGGraphics2D(OutSVGCarto.getSvgDocument());
                FileWriter WRFile = new FileWriter(new File(OutFilePath));
                OutSVGGraphics2D.stream(OutSVGCarto.getSvgDocument().getDocumentElement(),WRFile);
                break;
            case "png":
                FXMLLoader fXMLLoader1 = new FXMLLoader(getClass().getResource("InPutDlg/SavePicControlDlg.fxml"));
                Parent root1=fXMLLoader1.load();
                Scene scene1 = new Scene(root1);
                Stage stage1 = new Stage();
                stage1.setTitle("图像设置");
                stage1.setScene(scene1);
                stage1.showAndWait();

                SavePicControlDlgController MyController=new SavePicControlDlgController();
                MyController=fXMLLoader1.getController();
                SavePicControl SPC1=MyController.getSPC();
                
                
                PNGTranscoder PNGtranscoder = new PNGTranscoder();
                TranscoderInput input1 = new TranscoderInput(OutSVGCarto.getSvgDocument());
                OutputStream ostream1 = new FileOutputStream(OutFilePath);
                TranscoderOutput output1 = new TranscoderOutput(ostream1);
                //PNGtranscoder.addTranscodingHint(PNGTranscoder.KEY_QUALITY, new Float(SPC1.getQUALITY()));
                PNGtranscoder.addTranscodingHint(PNGTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float(SPC1.getPIXEL_UNIT_TO_MILLIMETER()));
                PNGtranscoder.transcode(input1, output1);
                ostream1.flush();
                ostream1.close();
                break;
            case "jpg":
                FXMLLoader fXMLLoader2 = new FXMLLoader(getClass().getResource("InPutDlg/SavePicControlDlg.fxml"));
                Parent root2=fXMLLoader2.load();
                Scene scene2 = new Scene(root2);
                Stage stage2 = new Stage();
                stage2.setTitle("图像设置");
                stage2.setScene(scene2);
                stage2.showAndWait();

                SavePicControlDlgController MyController2=new SavePicControlDlgController();
                MyController2=fXMLLoader2.getController();
                SavePicControl SPC2=MyController2.getSPC();
                
                
                JPEGTranscoder JPGtranscoder = new JPEGTranscoder();
                TranscoderInput input2 = new TranscoderInput(OutSVGCarto.getSvgDocument());
                OutputStream ostream2 = new FileOutputStream(OutFilePath);
                TranscoderOutput output2 = new TranscoderOutput(ostream2);
                JPGtranscoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(SPC2.getQUALITY()));
                JPGtranscoder.addTranscodingHint(JPEGTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float(SPC2.getPIXEL_UNIT_TO_MILLIMETER()));
                JPGtranscoder.transcode(input2, output2);
                ostream2.flush();
                ostream2.close();
                break;
            case "pdf":
                FXMLLoader fXMLLoader3 = new FXMLLoader(getClass().getResource("InPutDlg/SavePicControlDlg.fxml"));
                Parent root3=fXMLLoader3.load();
                Scene scene3 = new Scene(root3);
                Stage stage3 = new Stage();
                stage3.setTitle("图像设置");
                stage3.setScene(scene3);
                stage3.showAndWait();

                SavePicControlDlgController MyController3=new SavePicControlDlgController();
                MyController3=fXMLLoader3.getController();
                SavePicControl SPC3=MyController3.getSPC();
                
                
                
                
                PDFTranscoder PDFtranscoder = new PDFTranscoder();
                TranscoderInput input3 = new TranscoderInput(OutSVGCarto.getSvgDocument());
                OutputStream ostream3 = new FileOutputStream(OutFilePath);
                TranscoderOutput output3 = new TranscoderOutput(ostream3);
                //PDFtranscoder.addTranscodingHint(PDFTranscoder.KEY_QUALITY, new Float(SPC3.getQUALITY()));
                PDFtranscoder.addTranscodingHint(PDFTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float(SPC3.getPIXEL_UNIT_TO_MILLIMETER()));
                PDFtranscoder.transcode(input3, output3);
                ostream3.flush();
                ostream3.close();
                break;
            default:
                break;
        }
    }
    
    
    public void SetTOCTreeVew(SVGCarto S,TreeView<String> UIMainTOC){
        SVGDocument d=S.getSvgDocument();
        String STest=S.getBasedSVGName();
        TreeItem<String> rootitem=new TreeItem<>(STest);
        NodeList NL=d.getRootElement().getChildNodes();
        getItemString(rootitem,NL);
        UIMainTOC.setRoot(rootitem);
    }
    
    public boolean isSVGElementNodeName(String NodeName){
        switch (NodeName){
            case "#text":
            case "metadata":
            case "defs":
            case "style":
            case "#cdata-section":
            case "\n  ":
                return false;
            default:
                return true;
        }
    }
    private void getItemString(TreeItem<String> rootitem,NodeList tNodeList){
        for(int i=0;i<tNodeList.getLength();i++){
            Node N=tNodeList.item(i);
            String STest=N.getNodeName();
            if(isSVGElementNodeName(STest)){
                String Eid=((Element)N).getAttribute("id");
                TreeItem<String> titem;
                if(Eid==""){
                    titem=new TreeItem<>(STest);
                }
                else{
                    titem=new TreeItem<>(STest+"_"+Eid);
                }
                NodeList TNL=N.getChildNodes();
                getItemString(titem,TNL);
                rootitem.getChildren().add(titem);
            }
        }
    }
    
    
    public S1SelectMapController Step1ChooseBaseMap(MBasemap tBM) throws IOException{
        FXMLLoader fXMLLoader1 = new FXMLLoader(getClass().getResource("ITMCarto/S1SelectMap.fxml"));
        Parent root1=fXMLLoader1.load();
        S1SelectMapController MyController;
        MyController=fXMLLoader1.getController();
        if(tBM!=null){
            MyController.setMBasemap(tBM);
        }
        Scene scene1 = new Scene(root1);
        Stage stage1 = new Stage();
        stage1.setTitle("选择底图");
        stage1.setScene(scene1);
        stage1.showAndWait();
        return MyController;
    }
    
    public S2InputDataController Step2InputData(List<BaseData> tBDList) throws IOException{
        FXMLLoader fXMLLoader1 = new FXMLLoader(getClass().getResource("ITMCarto/S2InputData.fxml"));
        Parent root1=fXMLLoader1.load();
        S2InputDataController MyController;
        MyController=fXMLLoader1.getController();
        if(tBDList!=null){
            MyController.SetDataList(tBDList);
        }
        Scene scene1 = new Scene(root1);
        Stage stage1 = new Stage();
        stage1.setTitle("数据导入");
        stage1.setScene(scene1);
        stage1.showAndWait();
        return MyController;
    }
    
    public S3SelectionTypeController Step3SelectionType(List<CartoType> tCartoTypeList) throws IOException{
        FXMLLoader fXMLLoader1 = new FXMLLoader(getClass().getResource("ITMCarto/S3SelectionType.fxml"));
        Parent root1=fXMLLoader1.load();
        S3SelectionTypeController MyController;
        MyController=fXMLLoader1.getController();
        if(tCartoTypeList!=null){
            MyController.SetCartoTypeList(tCartoTypeList);
        }
        Scene scene1 = new Scene(root1);
        Stage stage1 = new Stage();
        stage1.setTitle("类型选择");
        stage1.setScene(scene1);
        stage1.showAndWait();
        return MyController;
    }
    
    public SHierarchicalStatisticalGraphController SHierarchicalStatisticalGraph(List<BaseData> tBaseData) throws IOException{
        FXMLLoader fXMLLoader1 = new FXMLLoader(getClass().getResource("ITMCarto/SHierarchicalStatisticalGraph.fxml"));
        Parent root1=fXMLLoader1.load();
        SHierarchicalStatisticalGraphController MyController;
        MyController=fXMLLoader1.getController();
        MyController.SetBaseData(tBaseData);
        
        Scene scene1 = new Scene(root1);
        Stage stage1 = new Stage();
        stage1.setTitle("类型选择");
        stage1.setScene(scene1);
        stage1.showAndWait();
        return MyController;
    }
    
    public SPartitionSatisticalGraphController SPartitionSatisticalGraph(List<BaseData> tBaseData) throws IOException{
        FXMLLoader fXMLLoader1 = new FXMLLoader(getClass().getResource("ITMCarto/SPartitionSatisticalGraph.fxml"));
        Parent root1=fXMLLoader1.load();
        SPartitionSatisticalGraphController MyController;
        MyController=fXMLLoader1.getController();
        MyController.setBaseData(tBaseData);
        
        Scene scene1 = new Scene(root1);
        Stage stage1 = new Stage();
        stage1.setTitle("类型选择");
        stage1.setScene(scene1);
        stage1.showAndWait();
        return MyController;
    }
    
    
}


